package com.vuestart.shushan.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vuestart.common.utils.HttpUtils;
import com.vuestart.shushan.member.dao.MemberLevelDao;
import com.vuestart.shushan.member.dao.MemberReceiveAddressDao;
import com.vuestart.shushan.member.entity.MemberLevelEntity;
import com.vuestart.shushan.member.entity.MemberReceiveAddressEntity;
import com.vuestart.shushan.member.exception.PhoneExistException;
import com.vuestart.shushan.member.exception.UserNameExistException;
import com.vuestart.shushan.member.service.MemberReceiveAddressService;
import com.vuestart.shushan.member.vo.MemberLoginVo;
import com.vuestart.shushan.member.vo.MemberRegitVo;
import com.vuestart.shushan.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vuestart.common.utils.PageUtils;
import com.vuestart.common.utils.Query;

import com.vuestart.shushan.member.dao.MemberDao;
import com.vuestart.shushan.member.entity.MemberEntity;
import com.vuestart.shushan.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Autowired
    MemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    MemberReceiveAddressDao memberReceiveAddressDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    // 注册
    @Override
    public void regist(MemberRegitVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();


        //1、设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //2、设置传过来的基本信息 检查用户名 手机号 是否唯一 ,为了让controller能感知异常
        checkPhoneUnique(vo.getPhone()); // 检查是否已有
        checkUserNameUnique(vo.getUserName());// 检查是否已有

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

        // todo 密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        // 其他的默认信息。。。
        entity.setNickname(vo.getUserName());
        entity.setEmail("m18275578687@163.com");
        entity.setHeader("默认头像");
        int rd=Math.random()>0.5?1:0;
        entity.setGender(rd);
        entity.setBirth(new Date());
        entity.setCity("重庆市");
        entity.setJob("暂无");
        entity.setSign("默认签名");
        entity.setSign("本地登录");
        entity.setIntegration(550);
        entity.setGrowth(500);
        entity.setCreateTime(new Date());
        entity.setSocialUid(UUID.randomUUID().toString());

        // 保存进数据库
        memberDao.insert(entity);

        MemberReceiveAddressEntity receiveAddressEntity = new MemberReceiveAddressEntity();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));

        receiveAddressEntity.setName(vo.getUserName());
        receiveAddressEntity.setMemberId(memberEntity.getId());
        receiveAddressEntity.setPhone(vo.getPhone());
        receiveAddressEntity.setProvince("重庆市");
        receiveAddressEntity.setCity("重庆市");
        receiveAddressEntity.setRegion("永川区");
        receiveAddressEntity.setDetailAddress("光彩大道368号");
        receiveAddressEntity.setDefaultStatus(1);


//        memberReceiveAddressService.save(receiveAddressEntity);
        memberReceiveAddressDao.insert(receiveAddressEntity);
    }

    // 检查手机号和用户名是否唯一
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    // 检查手机号和用户名是否唯一
    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameExistException();
        }
    }

    //用户登录
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        // 1、去数据库查询 SELECT * FROM `ums_member` WHERE username=? OR mobile=?
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity == null) {
            // 登录失败 查无此用户
            return null;
        }else {
            // 获取大哦数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            }else {
                return null;
            }
        }
    }

    // todo 社交登录 因审核原因 暂且搁置
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //注册和登录合并逻辑
        String uid = socialUser.getUid();

        // 判断当前社交用户是否登陆过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 1 用户已注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());

            return memberEntity;
        }else {
            // 2 无用户信息 进行注册
            MemberEntity regist = new MemberEntity();

            try {
                // 3 查出当前社交账号信息
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    // 当前社交账号的昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    // ....
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);
                    // ...... 可以获取更多信息
                }
            }catch (Exception e){

            }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());

            memberDao.insert(regist);

            return regist;
        }

    }


}